package com.cl.mycontroller;

import cn.hutool.json.JSONUtil;
import com.cl.annotation.ClComponent;
import com.cl.annotation.ClRequestParam;
import com.cl.container.ClBean;
import com.cl.container.ClController;
import com.cl.container.MyContainer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/*
* 前置 转发 控制器,将所有的请求转发至对应的controller上
* */
@WebServlet("/")
public class CLDisPatcherServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String requestURI = req.getRequestURI();
        String contextPath = req.getServletContext().getContextPath();

        //判断项目路径是否为空,不为空则 截取掉 项目路径
        if (!contextPath.equals("")){
            requestURI = requestURI.substring(contextPath.length());
        }

        /*
        * 找到目标controller
        * */
        ClController clController = MyContainer.getClController(requestURI);
        Object object = clController.getObject();
        Method controllerMethod = clController.getControllerMethod();

        /*
        *  分析controller入参参数
        * */
        Object[] objects = analyseParameters(controllerMethod, req);

        try {
            /*
            调用目标方法,传入参数
            * 方法返回参数,转成json返回
            *
            * */
            Object invoke = controllerMethod.invoke(object,objects);
            if (controllerMethod.getReturnType() != Void.class){
                responseJson(resp,invoke);
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }


    /*
    * 分析controller方法入参参数
    * */
    private Object[] analyseParameters(Method controllerMethod,HttpServletRequest request){

        //1.先获取请求参数(GET)
        Map<String, String[]> parameterMap = request.getParameterMap();
        int parameterCount = controllerMethod.getParameterCount();
        Class<?>[] parameterTypes = controllerMethod.getParameterTypes();
        //
        Annotation[][] parameterAnnotations = controllerMethod.getParameterAnnotations();

        //实参 数组
        Object[] objects = new Object[parameterCount];

        /*
        * 方法中的参数的注解
        * */
        for (int i = 0; i < parameterAnnotations.length; i++) {
            for (int j=0 ; j<parameterAnnotations[i].length;j++){
                Annotation annotation = parameterAnnotations[i][j];
                Class<? extends Annotation> aClass = annotation.annotationType();
                if (aClass == ClRequestParam.class){
                   ClRequestParam clRequestParam = (ClRequestParam)annotation;
                    String value = clRequestParam.value();
                    System.out.println("注解参数名"+value);
                    //从请求参数map中获取值
                    String[] strings = parameterMap.get(value);
                    if (strings != null && strings.length>0){
                        //查看形参数组中的当前位置是否是数组类型参数
                        if (parameterTypes[i] == String[].class){
                            objects[i] = strings;
                        }else {
                            objects[i] = strings[0];
                        }
                    }
                    //去容器中获取值
                }else if (aClass == ClComponent.class){
                    ClComponent clComponent = (ClComponent) annotation;
                    ClBean beanWithContainer = MyContainer.getBeanWithContainer(clComponent.value(), parameterTypes[i]);
                    objects[i] = beanWithContainer.getObject();
                }
            }
        }
        return objects;
    }

    /*
    * 响应JSON
    * */
    private void responseJson(HttpServletResponse resp,Object object){
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String s = JSONUtil.toJsonStr(object);
        writer.write(s);
        writer.flush();
        writer.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    public void init() throws ServletException {
        super.init();
    }
}
